package org.gwtmultipage.sample.server;

import javax.servlet.http.HttpSession;

import hr.fer.zemris.rznu.model.dto.user.UserDTO;

import org.gwtmultipage.sample.client.LoginService;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class LoginServiceImpl extends RemoteServiceServlet implements LoginService{
	private static final String USER_SESSION = "User";
	private static final long serialVersionUID = 1L;

	public UserDTO checkLogin(String userName, String password) throws IllegalArgumentException {
		if (userName.equalsIgnoreCase("zexinho")) { // Check the database
		       UserDTO user = new UserDTO();
		       user.setUsername(userName);
		       setUserInSession(user);
		       return user;
		    } else
		       return null;
	}
	
	private void setUserInSession(UserDTO user) {
	    HttpSession session = getThreadLocalRequest().getSession();
	    session.setAttribute(USER_SESSION, user);
	}
	 
	private UserDTO getUserFromSession() {
	    HttpSession session = getThreadLocalRequest().getSession();
	    return (UserDTO) session.getAttribute(USER_SESSION);
	}
	
	public void logout() {
		HttpSession session = getThreadLocalRequest().getSession();
		if (session != null)
			session.removeAttribute(USER_SESSION);
	}
	
	public UserDTO isUserLogged() {
		UserDTO user = getUserFromSession();
		if (user != null) {
			return user;
		}
		return null;
	}
}
